package luke4fun.wheresmymoney.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

import luke4fun.wheresmymoney.domain.Item;

public class ItemDAO {

	private static ItemDAO instance = null;
	
	private ItemDAO() {}
	
	public static ItemDAO getInstance() {
		if (instance == null) {
			instance = new ItemDAO();
		}
		
		return instance;
	}
	
	public List<Item> queryItem(SQLiteDatabase db, String item) {
		List<Item> list = new ArrayList<Item>();
		Cursor cursor = null;
		if (item != null && item.length() > 0) {
			cursor = db.query(DBConstants.TABLE_ITEM, null, DBConstants.ITEM_NAME + "=?",
				new String[] { item }, null, null, null);
		} else {
			cursor = db.query(DBConstants.TABLE_ITEM, null, null, null, null, null, null);
		}
		
		while (cursor.moveToNext()) {
			Item it = new Item();
			it.setId(cursor.getLong(cursor.getColumnIndex(DBConstants.ITEM_ID)));
			it.setName(cursor.getString(cursor.getColumnIndex(DBConstants.ITEM_NAME)));
			
			list.add(it);
		}
		return list;
	}
	
	public long insertItem(SQLiteDatabase db, String item) {
		ContentValues cv = new ContentValues();
		cv.put(DBConstants.ITEM_NAME, item);
		return db.insert(DBConstants.TABLE_ITEM, null, cv);
	}
}
